/**
 * Created by YESO on 2016/2/19.
 */
angular.module('app.shop', [
])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('home.shoplist', {
            url: '/shop/list',
            templateUrl: "tpls/shop/list.html",
            controller: 'ShopController'
        })
        .state('home.shopimport', {
            url: '/shop/import',
            templateUrl: "tpls/shop/import_product_shop.html",
            controller: 'ShopImportController'
        })
        .state('home.shopmateriallist', {
            url: '/shop/listmaterial',
            templateUrl: "tpls/shop/list_material.html",
            controller: 'ListMaterialShopController'
        })
        .state('home.shopimportmaterial', {
            url: '/shop/importmaterial',
            templateUrl: "tpls/shop/import_material_shop.html",
            controller: 'ImportMaterialShopController'
        })
}])

.controller('ShopController', ['$scope','ShopListService','CountyShopService', function($scope, ShopListService, CountyShopService) {
    $scope.shops = [];
    ShopListService.getshoplist(330329).$promise.then(function(list){
        for (var i=0;i<list.length;i++) {
            var townshops = list[i];
            for (var j=0;j<townshops.shops.length;j++) {
                var shop = townshops.shops[j];
                shop.townname = townshops.name;
                $scope.shops.push(shop);
            }
        }
    });
    //
    $scope.remove = function(shopid) {
        //console.log(shopid);
        // 只删除引用，并不真正删除店铺
        CountyShopService.removecountytownshop(shopid).$promise.then(function(data){
            window.location.reload();
        });
    }
}])

.controller('ListMaterialShopController', ['$scope','ShopGroupService','GroupShopService', function($scope, ShopGroupService, GroupShopService) {
    $scope.shops = ShopGroupService.getgroupshoplist(10);
    //
    $scope.remove = function(shopid) {
        //console.log(shopid);
        // 只删除引用，并不真正删除店铺
        GroupShopService.removegroupshop(10, shopid).$promise.then(function(data){
            window.location.reload();
        });
    }
}])

.controller('ShopImportController', ['$scope','ShopService','CountyService','CountyShopService', function($scope, ShopService, CountyService, CountyShopService) {
    $(function () {
        $('#doc-form-file').on('change', function () {
            var fileNames = '';
            $.each(this.files, function () {
                fileNames += '<span class="am-badge">' + this.name + '</span> ';
            });
            $('#file-list').html(fileNames);
        });
        //
        $('.am-alert').alert();
    });
  
  $scope.alert_msg = "";
  $scope.enable_submit = false;
  $scope.close_alert = function() {
      $scope.alert_msg = "";
  }
  //
  $scope.readFile = function () {
        function process_wb(wb) {
            var workbook = ExcelImporter.to_json(wb);
            var county_map = {};
            var town_map = {};
            $scope.shops = new Array();
            $scope.$apply(function () {
                $scope.rows = workbook['Sheet1'];
                for (var i = 0; i < $scope.rows.length; i++) {
                    var shop = {};
                    shop.name = $scope.rows[i].商店名称;
                    shop.address = $scope.rows[i].商店具体地址;
                    shop.county = $scope.rows[i].商店所在县城;
                    shop.town = $scope.rows[i].商店所在城镇;
                    shop.tel = $scope.rows[i].联系电话;
                    shop.logo = $scope.rows[i].商店logo;
                    shop.notice = $scope.rows[i].商店公告;
                    shop.lowPrice = $scope.rows[i].起送价;
                    shop.deviceId = $scope.rows[i].订单机ID;
                    shop.seq=10;
                    $scope.shops.push(shop);
                }
                //console.log($scope.shops);
                prepare_county($scope.shops, 0);
                //准备必要数据到map备用
                function prepare_town(list, i) {
                    //console.log('prepare_town() i='+i)
                    if (i >= list.length) {
                        //console.log(town_map);
                        //console.log($scope.shops);
                        $scope.enable_submit = true;
                        return;
                    }
                    var item = list[i];
                    if (!item.town) {
                        $scope.alert_msg = '"商店所在城镇"不能留空，请检查数据！';
                        return;
                    }
                    if (town_map[item.town]) {
                        item.townid = town_map[item.town];
                        prepare_town(list, i + 1);
                    } else {
                        //console.log('gettownbyname: '+item.town);
                        CountyService.gettownbyname(item.countyid, item.town).$promise.then(function (data) {
                            item.townid = data.townid;
                            town_map[item.town] = data.townid;
                            prepare_town(list, i + 1);
                        }, function(msg){
                            console.log(msg);
                            $scope.alert_msg = '查询"商店所在城镇"失败，请检查数据！';
                        })
                    }
                }
                //准备必要数据到map备用
                function prepare_county(list, i) {
                    //console.log('prepare_county() i='+i)
                    if (i >= list.length) {
                        //console.log(county_map);
                        prepare_town($scope.shops, 0);
                        return;
                    }
                    var item = list[i];
                    //console.log(item);
                    if (!item.county) {
                        $scope.alert_msg = '"商店所在县城"不能留空，请检查数据！';
                        return;
                    }
                    if (county_map[item.county]) {
                        item.countyid = county_map[item.county];
                        prepare_county(list, i + 1);
                    } else {
                        //console.log('getcountybyname: '+item.county);
                        CountyService.getcountybyname(item.county).$promise.then(function (data) {
                            item.countyid = data.countyid;
                            county_map[item.county] = data.countyid;
                            prepare_county(list, i + 1);
                        }, function(msg){
                            console.log(msg);
                            $scope.alert_msg = '查询"商店所在县城"失败，请检查数据！';
                        })
                    }
                }
            });
        }

        var target = document.getElementById('doc-form-file');
        var files = target.files;
        var f = files[0];
        ExcelImporter.importexcel(f, process_wb);
    }

    $scope.submit = function () {
        //console.log($scope.shops);
        addshop($scope.shops, 0);
        function addshop(list, i) {
            if (i >= list.length) {
                addcounttownshop($scope.shops, 0);
                return;
            }
            var item = list[i];
            ShopService.addshop(item, function (data) {
                $scope.shops[i].shopid = data.shopid;
                addshop(list, i + 1);
            }, function (data) {
            });
        }

        function addcounttownshop(list, i) {
            if (i >= list.length) {
                alert("导入成功！");
                window.location.reload();
                return;
            }
            var item = list[i];
            var counttownshop = {countyid:item.countyid, townid:item.townid, shopid:item.shopid};
            CountyShopService.addcountytownshop(counttownshop, function (data) {
                addcounttownshop(list, i+1);
            }, function (data) {
                //window.location.reload();
                alert("导入失败！");
                return;
            });
        }
    }

}])

.controller('ImportMaterialShopController', ['$scope','ShopService','GroupService','GroupShopService', function($scope, ShopService, GroupService, GroupShopService) {
    $(function () {
        $('#doc-form-file').on('change', function () {
            var fileNames = '';
            $.each(this.files, function () {
                fileNames += '<span class="am-badge">' + this.name + '</span> ';
            });
            $('#file-list').html(fileNames);
        });
        //
        $('.am-alert').alert();
    });
  
  $scope.alert_msg = "";
  $scope.enable_submit = false;
  $scope.close_alert = function() {
      $scope.alert_msg = "";
  }
  //
  $scope.readFile = function () {
        function process_wb(wb) {
            var workbook = ExcelImporter.to_json(wb);
            var group_map = {};
            $scope.shops = new Array();
            $scope.$apply(function () {
                $scope.rows = workbook['Sheet1'];
                for (var i = 0; i < $scope.rows.length; i++) {
                    var shop = {};
                    shop.name = $scope.rows[i].商店名称;
                    shop.address = $scope.rows[i].商店具体地址;
                    shop.group = $scope.rows[i].商店分组;
                    shop.tel = $scope.rows[i].联系电话;
                    shop.logo = $scope.rows[i].商店logo;
                    shop.notice = $scope.rows[i].商店公告;
                    shop.lowPrice = $scope.rows[i].起送价;
                    shop.deviceId = $scope.rows[i].订单机ID;
                    shop.seq=10;
                    $scope.shops.push(shop);
                }
                //console.log($scope.shops);
                prepare_group($scope.shops, 0);
                //准备必要数据到map备用
                function prepare_group(list, i) {
                    //console.log('prepare_group() i='+i)
                    if (i >= list.length) {
                        console.log(group_map);
                        $scope.enable_submit = true;
                        return;
                    }
                    var item = list[i];
                    //console.log(item);
                    if (!item.group) {
                        $scope.alert_msg = '"商店分组"不能留空，请检查数据！';
                        return;
                    }
                    if (group_map[item.group]) {
                        item.groupid = group_map[item.group];
                        prepare_group(list, i + 1);
                    } else {
                        //console.log('getgroupbyname: '+item.group);
                        GroupService.getgroupbyname(item.group).$promise.then(function (data) {
                            item.groupid = data.groupid;
                            group_map[item.group] = data.groupid;
                            prepare_group(list, i + 1);
                        }, function(msg){
                            console.log(msg);
                            $scope.alert_msg = '查询"商店分组"失败，请检查数据！';
                        })
                    }
                }
            });
        }

        var target = document.getElementById('doc-form-file');
        var files = target.files;
        var f = files[0];
        ExcelImporter.importexcel(f, process_wb);
    }

    $scope.submit = function () {
        //console.log($scope.shops);
        addshop($scope.shops, 0);
        function addshop(list, i) {
            if (i >= list.length) {
                addgroupshop($scope.shops, 0);
                return;
            }
            var item = list[i];
            ShopService.addshop(item, function (data) {
                $scope.shops[i].shopid = data.shopid;
                addshop(list, i + 1);
            }, function (data) {
            });
        }

        function addgroupshop(list, i) {
            if (i >= list.length) {
                alert("导入成功！");
                window.location.reload();
                return;
            }
            var item = list[i];
            var groupshop = {groupid:item.groupid, shopid:item.shopid};
            GroupShopService.addgroupshop(groupshop, function (data) {
                addgroupshop(list, i+1);
            }, function (data) {
                //window.location.reload();
                alert("导入失败！");
                return;
            });
        }
    }

}])
;